import 'package:get/get.dart';
import 'package:industry_net/pages/msg/chat/models/chat.dart';
import 'package:industry_net/base/common/img_util.dart';
import 'package:industry_net/pages/me/main/models/usually.dart';
import 'index.dart';

class ChatController extends GetxController {
  ChatController();

  final state = ChatState();

  // tap
  void handleTap(int index) {
    Get.snackbar(
      "标题",
      "消息",
    );
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
    _obsever();
    _initData();
  }

  void _initData() {
    state.inputItems = [
      UsuallyModel(url: 'icon_photo.png'.imgPathMsg, name: '相册'),
      UsuallyModel(url: 'icon_camera.png'.imgPathMsg, name: '拍照'),
      UsuallyModel(url: 'icon_photo.png'.imgPathMsg, name: '相册'),
      UsuallyModel(url: 'icon_camera.png'.imgPathMsg, name: '拍照'),
      UsuallyModel(url: 'icon_photo.png'.imgPathMsg, name: '相册'),
      UsuallyModel(url: 'icon_camera.png'.imgPathMsg, name: '拍照'),
    ];
  }

  void _obsever() {
    state.focusNode.addListener(() {
      if (state.focusNode.hasFocus) {
        if (state.isAdding) {
          state.isAdding = false;
          update();
        }
      }
    });

    state.chatBarController.addListener(() {
      if (state.isTextEditing != state.chatBarController.text.isNotEmpty) {
        state.isTextEditing = state.chatBarController.text.isNotEmpty;
        update();
      }
    });
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    var _index = Runes('\u{1f44f} \u{1F601}');
    var _unicodeStr = String.fromCharCodes(_index);
    state.list = [
      ChatModel()
        ..isSelf = false
        ..msgType = ChatMsgType.timeline
        ..msg = '2021.12.28 10:46',
      ChatModel()
        ..isSelf = true
        ..msgType = ChatMsgType.text
        ..msg = '你说的啥，再重复一遍,其实我是想让你换行，那你enter呀',
      ChatModel()
        ..isSelf = false
        ..msgType = ChatMsgType.text
        ..msg = _unicodeStr,
      ChatModel()
        ..isSelf = false
        ..msgType = ChatMsgType.image
        ..msg = 'please',
    ].reversed.toList();
    update();
    super.onReady();
  }

  void actionSend() {
    state.list.insert(
      0,
      ChatModel()
        ..isSelf = true
        ..msgType = ChatMsgType.text
        ..msg = state.chatBarController.text,
    );
    update();
    state.chatBarController.text = '';
  }

  void actionVoice() {}
  void actionEmjoi() {}
  void actionAdd() {
    state.isAdding = !state.isAdding;
    if (state.isAdding) {
      state.focusNode.unfocus();
    } else {
      state.focusNode.requestFocus();
    }
    update();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    state.focusNode.dispose();
    state.chatBarController.dispose();
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }
}
